package com.shangxia.monomer.common.util;

import com.alibaba.fastjson.JSONObject;
import com.shangxia.monomer.common.bean.BeanDemo;
import lombok.NonNull;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhouya38158
 * @Package com.shangxia.monomer.common.util
 * @date 2021/7/22 11:18
 */
public class ClassUtil {

    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException {
        List<String> list = getAllMethods(BeanDemo.class);
        for (String str : list) {
            System.out.println(str);
        }
//        Object beanDemo = createObject("com.shangxia.monomer.common.bean.BeanDemo");
//        System.out.println(JSONObject.toJSONString(beanDemo));
        BeanDemo beanDemo = new BeanDemo();
        System.out.println(BeanDemo.get5());
        System.out.println(JSONObject.toJSONString(beanDemo));
    }

    public static List<String> getAllMethods(@NonNull final Class<?> cls) {
        return Arrays.stream(cls.getDeclaredMethods())
                .map(Method::getName)
                .collect(Collectors.toList());
    }

    public static List<String> getAllPublicFieldNames(@NonNull final Class<?> cls) {
        return Arrays.stream(cls.getFields())
                .map(Field::getName)
                .collect(Collectors.toList());
    }

    public static List<String> getAllFieldNames(@NonNull final Class<?> cls) {
        List fields = new ArrayList<String>();
        Class currentCls = cls;
        while (currentCls != null) {
            fields.addAll(
                    Arrays.stream(currentCls.getDeclaredFields())
                            .filter(field -> !field.isSynthetic())
                            .map(Field::getName)
                            .collect(Collectors.toList()));
            currentCls = currentCls.getSuperclass();
        }
        return fields;
    }

    public static <T> T createObject(String cls)
            throws NoSuchMethodException,
            IllegalAccessException,
            InvocationTargetException,
            InstantiationException,
            ClassNotFoundException {
        Class<?> aClass = Class.forName(cls);
        Constructor<?> constructor = aClass.getConstructor();
        return (T) constructor.newInstance();
    }
}
